package outbound_crowd

import (
	"context"
	"git.mycaigou.com/gfyx/common/authorize"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	dto "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/market"
	marketResp "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/repository/market"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/utils"
	pb "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/market"
	"git.myscrm.cn/golang/common/ykerrcode"
	"git.myscrm.cn/golang/stark/v4"
	"strings"
)

type outboundCrowdService struct {
	outboundCrowdRepo marketResp.OutboundCrowdRepositoryIface
}

// NewOutboundCrowdService
// 外呼，人群
func NewOutboundCrowdService(outboundCrowdRepo marketResp.OutboundCrowdRepositoryIface) OutboundCrowdServiceIface {
	return &outboundCrowdService{
		outboundCrowdRepo: outboundCrowdRepo,
	}
}

// GetCrowdList 人群列表
func (s *outboundCrowdService) GetCrowdList(ctx context.Context, request *dto.GetCrowdListRequest) (*dto.GetCrowdListResponse, error) {
	requestPb := &pb.GetCrowdListRequest{
		CrowdName: request.CrowdName,
		Status:    request.Status,
		Page:      request.Page,
		PageSize:  request.PageSize,
	}
	resPb, err := s.outboundCrowdRepo.GetCrowdList(ctx, requestPb)
	res := &dto.GetCrowdListResponse{
		List: []*dto.GetCrowdListData{},
	}
	if err != nil {
		stark.Logger.Error(ctx, "GetCrowdList，失败:", err)
		return res, err
	}
	res.Total = resPb.Total
	for _, item := range resPb.List {
		crowdItem := s.dealCrowdData(item)
		res.List = append(res.List, crowdItem)
	}
	return res, nil
}
func (s *outboundCrowdService) dealCrowdData(crowd *pb.GetCrowd) *dto.GetCrowdListData {
	res := &dto.GetCrowdListData{
		Id:                    crowd.Id,
		CrowdName:             crowd.CrowdName,
		Type:                  crowd.Type,
		Status:                crowd.Status,
		Version:               crowd.Version,
		WinbidDateStart:       crowd.WinbidDateStart,
		WinbidDateEnd:         crowd.WinbidDateEnd,
		PhoneType:             strings.Split(crowd.PhoneType, ","),
		EveryCompanyNum:       crowd.EveryCompanyNum,
		BidDateStart:          crowd.BidDateStart,
		BidDateEnd:            crowd.BidDateEnd,
		IsLandOpen:            crowd.IsLandOpen,
		LandDateStart:         crowd.LandDateStart,
		LandDateEnd:           crowd.LandDateEnd,
		IsBuildingOpen:        crowd.IsBuildingOpen,
		BuildingDateStart:     crowd.BuildingDateStart,
		BuildingDateEnd:       crowd.BuildingDateEnd,
		IsSaleOpen:            crowd.IsSaleOpen,
		SaleDateStart:         crowd.SaleDateStart,
		SaleDateEnd:           crowd.SaleDateEnd,
		CreatedOn:             crowd.CreatedOn,
		CreatedBy:             crowd.CreatedBy,
		CompanyTotal:          crowd.CompanyTotal,
		ContactTotal:          crowd.ContactTotal,
		AreaCode:              crowd.AreaCode,
		AreaName:              crowd.AreaName,
		WinbidKeyword:         crowd.WinbidKeyword,
		CompanyKeyword:        crowd.CompanyKeyword,
		BidKeyword:            crowd.BidKeyword,
		BidKeywordExclude:     crowd.BidKeywordExclude,
		LandUsage:             crowd.LandUsage,
		BuildingType:          crowd.BuildingType,
		SaleType:              crowd.SaleType,
		LogicType:             crowd.LogicType,
		IsBidOpen:             crowd.IsBidOpen,
		LandKeyword:           crowd.LandKeyword,
		BuildingKeyword:       crowd.BuildingKeyword,
		SaleKeyword:           crowd.SaleKeyword,
		CompanyType:           crowd.CompanyType,
		CompanyKeywordExclude: crowd.CompanyKeywordExclude,
	}
	if res.AreaCode == nil {
		res.AreaCode = []string{}
	}
	if res.AreaName == nil {
		res.AreaName = []string{}
	}
	if res.WinbidKeyword == nil {
		res.WinbidKeyword = []string{}
	}
	if res.CompanyKeyword == nil {
		res.CompanyKeyword = []string{}
	}
	if res.BidKeyword == nil {
		res.BidKeyword = []string{}
	}
	if res.BidKeywordExclude == nil {
		res.BidKeywordExclude = []string{}
	}
	if res.LandUsage == nil {
		res.LandUsage = []string{}
	}
	if res.BuildingType == nil {
		res.BuildingType = []string{}
	}
	if res.SaleType == nil {
		res.SaleType = []string{}
	}
	if res.LandKeyword == nil {
		res.LandKeyword = []string{}
	}
	if res.BuildingKeyword == nil {
		res.BuildingKeyword = []string{}
	}
	if res.SaleKeyword == nil {
		res.SaleKeyword = []string{}
	}
	if res.CompanyType == nil {
		res.CompanyType = []string{}
	}
	if res.CompanyKeywordExclude == nil {
		res.CompanyKeywordExclude = []string{}
	}

	if crowd.PhoneType != "" {
		res.PhoneType = strings.Split(crowd.PhoneType, ",")
	} else {
		res.PhoneType = make([]string, 0)
	}

	return res
}

func (s *outboundCrowdService) GetCrowdDetail(ctx context.Context, request *dto.GetCrowdDetailRequest) (*dto.GetCrowdListData, error) {
	requestPb := &pb.GetCrowdDetailRequest{
		Id: request.Id,
	}
	resPb, err := s.outboundCrowdRepo.GetCrowdDetail(ctx, requestPb)
	if resPb == nil || resPb.Data == nil || resPb.Data.Id == 0 {
		return &dto.GetCrowdListData{}, ykerrcode.TogRPCError(errcode.COMMON_DATA_NOT_EXIST, "找不到相应数据")
	}
	if err != nil {
		stark.Logger.Error(ctx, "GetCrowdDetail，失败:", err)
		return &dto.GetCrowdListData{}, err
	}
	res := s.dealCrowdData(resPb.Data)
	return res, nil
}

func (s *outboundCrowdService) AddCrowd(ctx context.Context, request *dto.AddCrowdRequest) (*dto.AddCrowdResponse, error) {
	requestPb := &pb.AddCrowdRequest{
		Id:                    request.Id,
		CrowdName:             request.CrowdName,
		Type:                  request.Type,
		AreaCode:              request.AreaCode,
		AreaName:              request.AreaName,
		WinbidKeyword:         request.WinbidKeyword,
		CompanyKeyword:        request.CompanyKeyword,
		WinbidDateStart:       request.WinbidDateStart,
		WinbidDateEnd:         request.WinbidDateEnd,
		PhoneType:             strings.Join(request.PhoneType, ","),
		EveryCompanyNum:       request.EveryCompanyNum,
		BidKeyword:            request.BidKeyword,
		BidKeywordExclude:     request.BidKeywordExclude,
		BidDateStart:          request.BidDateStart,
		BidDateEnd:            request.BidDateEnd,
		IsLandOpen:            request.IsLandOpen,
		LandUsage:             request.LandUsage,
		LandDateStart:         request.LandDateStart,
		LandDateEnd:           request.LandDateEnd,
		IsBuildingOpen:        request.IsBuildingOpen,
		BuildingType:          request.BuildingType,
		BuildingDateStart:     request.BuildingDateStart,
		BuildingDateEnd:       request.BuildingDateEnd,
		IsSaleOpen:            request.IsSaleOpen,
		SaleType:              request.SaleType,
		SaleDateStart:         request.SaleDateStart,
		SaleDateEnd:           request.SaleDateEnd,
		CompanyTotal:          request.CompanyTotal,
		ContactTotal:          request.ContactTotal,
		LogicType:             request.LogicType,
		IsBidOpen:             request.IsBidOpen,
		LandKeyword:           request.LandKeyword,
		BuildingKeyword:       request.BuildingKeyword,
		SaleKeyword:           request.SaleKeyword,
		CompanyType:           request.CompanyType,
		CompanyKeywordExclude: request.CompanyKeywordExclude,
	}
	resPb, err := s.outboundCrowdRepo.AddCrowd(ctx, requestPb)
	res := &dto.AddCrowdResponse{}
	if err != nil {
		stark.Logger.Error(ctx, "AddCrowd，失败:", err)
		return res, err
	}
	res.Id = resPb.Id
	res.NewCrowd = resPb.NewCrowd
	return res, nil
}

func (s *outboundCrowdService) DeleteCrowd(ctx context.Context, request *dto.DeleteCrowdRequest) (*dto.DeleteCrowdResponse, error) {
	requestPb := &pb.DeleteCrowdRequest{
		Id: request.Id,
	}
	resPb, err := s.outboundCrowdRepo.DeleteCrowd(ctx, requestPb)
	res := &dto.DeleteCrowdResponse{}
	if err != nil {
		stark.Logger.Error(ctx, "DeleteCrowd，失败:", err)
		return res, err
	}
	res.Id = resPb.Id

	return res, nil
}

func (s *outboundCrowdService) GetCrowdByWinbid(ctx context.Context, request *dto.GetCrowdByWinbidRequest) (*dto.GetCrowdByWinbidResponse, error) {
	requestPb := &pb.GetCrowdByWinbidRequest{
		Page:                  request.Page,
		PageSize:              request.PageSize,
		AreaCode:              request.AreaCode,
		WinbidKeyword:         request.WinbidKeyword,
		CompanyKeyword:        request.CompanyKeyword,
		WinbidDateStart:       request.WinbidDateStart,
		WinbidDateEnd:         request.WinbidDateEnd,
		EveryCompanyNum:       request.EveryCompanyNum,
		ContactType:           strings.Join(request.ContactType, ","),
		LogicType:             request.LogicType,
		CompanyKeywordExclude: request.CompanyKeywordExclude,
	}
	resPb, err := s.outboundCrowdRepo.GetCrowdByWinbid(ctx, requestPb)

	res := &dto.GetCrowdByWinbidResponse{
		List: make([]*dto.GetCrowdByWinbidItem, 0),
	}
	if err != nil {
		stark.Logger.Error(ctx, "GetCrowdByWinbid，失败:", err)
		return res, err
	}
	res.Total = resPb.CompanyTotal
	res.ContactTotal = resPb.ContactTotal
	for _, item := range resPb.List {
		crowdItem := &dto.GetCrowdByWinbidItem{
			SupplierName:   item.SupplierName,
			OrganizingCode: item.OrganizingCode,
			CoopPrjName:    item.CoopPrjName,
			CoopProvince:   item.CoopProvince,
			CoopCity:       item.CoopCity,
		}
		contactList := make([]*dto.ContactInfo, 0)
		for _, v := range item.ContactList {
			data := &dto.ContactInfo{
				Name:        v.Name,
				PhoneNumber: utils.GetMobileEncrypt(v.PhoneNumber),
			}
			contactList = append(contactList, data)
		}
		crowdItem.ContactList = contactList

		res.List = append(res.List, crowdItem)
	}
	return res, nil
}

func (s *outboundCrowdService) CrowdDetailWinbid(ctx context.Context, request *dto.CrowdDetailWinbidRequest) (*dto.CrowdDetailByWinbidResponse, error) {
	requestPb := &pb.CrowdDetailWinbidRequest{
		Page:     request.Page,
		PageSize: request.PageSize,
		CrowdId:  request.CrowdId,
	}
	resPb, err := s.outboundCrowdRepo.CrowdDetailWinbid(ctx, requestPb)

	res := &dto.CrowdDetailByWinbidResponse{
		List: make([]*dto.GetCrowdByWinbidItem, 0),
	}
	if err != nil {
		stark.Logger.Error(ctx, "CrowdDetailWinbid，失败:", err)
		return res, err
	}
	res.Total = resPb.CompanyTotal
	res.ContactTotal = resPb.ContactTotal
	for _, item := range resPb.List {
		crowdItem := &dto.GetCrowdByWinbidItem{
			SupplierName:   item.SupplierName,
			OrganizingCode: item.OrganizingCode,
			CoopPrjName:    item.CoopPrjName,
			CoopProvince:   item.CoopProvince,
			CoopCity:       item.CoopCity,
		}
		contactList := make([]*dto.ContactInfo, 0)
		for _, v := range item.ContactList {
			data := &dto.ContactInfo{
				Name:        v.Name,
				PhoneNumber: utils.GetMobileEncrypt(v.PhoneNumber),
			}
			contactList = append(contactList, data)
		}
		crowdItem.ContactList = contactList

		res.List = append(res.List, crowdItem)
	}
	return res, nil
}

func (s *outboundCrowdService) GetCrowdByDeveloper(ctx context.Context, request *dto.GetCrowdByDeveloperRequest) (*dto.GetCrowdByDeveloperResponse, error) {
	requestPb := &pb.GetCrowdByDeveloperRequest{
		Page:                  request.Page,
		PageSize:              request.PageSize,
		AreaCode:              request.AreaCode,
		BidKeyword:            request.BidKeyword,
		BidKeywordExclude:     request.BidKeywordExclude,
		ProjectKeyword:        request.ProjectKeyword,
		BidDateStart:          request.BidDateStart,
		BidDateEnd:            request.BidDateEnd,
		LandUsage:             request.LandUsage,
		LandDateStart:         request.LandDateStart,
		LandDateEnd:           request.LandDateEnd,
		BuildingType:          request.BuildingType,
		BuildingDateStart:     request.BuildingDateStart,
		BuildingDateEnd:       request.BuildingDateEnd,
		SaleType:              request.SaleType,
		SaleDateStart:         request.SaleDateStart,
		SaleDateEnd:           request.SaleDateEnd,
		EveryCompanyNum:       request.EveryCompanyNum,
		ContactType:           strings.Join(request.ContactType, ","),
		IsLandOpen:            request.IsLandOpen,
		IsSaleOpen:            request.IsSaleOpen,
		IsBuildingOpen:        request.IsBuildingOpen,
		IsBidOpen:             request.IsBidOpen,
		LogicType:             request.LogicType,
		LandKeyword:           request.LandKeyword,
		BuildingKeyword:       request.BuildingKeyword,
		SaleKeyword:           request.SaleKeyword,
		CompanyType:           request.CompanyType,
		CompanyKeyword:        request.CompanyKeyword,
		CompanyKeywordExclude: request.CompanyKeywordExclude,
	}
	resPb, err := s.outboundCrowdRepo.GetCrowdByDeveloper(ctx, requestPb)

	res := &dto.GetCrowdByDeveloperResponse{
		List: make([]*dto.GetCrowdByDeveloperItem, 0),
	}
	if err != nil {
		stark.Logger.Error(ctx, "GetCrowdByWinbid，失败:", err)
		return res, err
	}
	res.Total = resPb.CompanyTotal
	res.ContactTotal = resPb.ContactTotal
	for _, item := range resPb.List {
		crowdItem := &dto.GetCrowdByDeveloperItem{
			DeveloperName:           item.DeveloperName,
			DeveloperOrganizingCode: item.DeveloperOrganizingCode,
			TakeLandCnt_1Year:       item.TakeLandCnt_1Year,
			SellProjectCnt_1Year:    item.SellProjectCnt_1Year,
			CommencePermitCnt_1Year: item.CommencePermitCnt_1Year,
			PurchaseDemandCnt_1Year: item.PurchaseDemandCnt_1Year,
		}
		contactList := make([]*dto.ContactInfo, 0)
		for _, v := range item.ContactList {
			data := &dto.ContactInfo{
				Name:        v.Name,
				PhoneNumber: utils.GetMobileEncrypt(v.PhoneNumber),
			}
			contactList = append(contactList, data)
		}
		crowdItem.ContactList = contactList

		res.List = append(res.List, crowdItem)
	}
	return res, nil
}

func (s *outboundCrowdService) CrowdDetailDeveloper(ctx context.Context, request *dto.CrowdDetailDeveloperRequest) (*dto.CrowdDetailDeveloperResponse, error) {
	requestPb := &pb.CrowdDetailDeveloperRequest{
		Page:     request.Page,
		PageSize: request.PageSize,
		CrowdId:  request.CrowdId,
	}
	resPb, err := s.outboundCrowdRepo.CrowdDetailDeveloper(ctx, requestPb)

	res := &dto.CrowdDetailDeveloperResponse{
		List: make([]*dto.GetCrowdByDeveloperItem, 0),
	}
	if err != nil {
		stark.Logger.Error(ctx, "CrowdDetailDeveloper，失败:", err)
		return res, err
	}
	res.Total = resPb.CompanyTotal
	res.ContactTotal = resPb.ContactTotal
	for _, item := range resPb.List {
		crowdItem := &dto.GetCrowdByDeveloperItem{
			DeveloperName:           item.DeveloperName,
			DeveloperOrganizingCode: item.DeveloperOrganizingCode,
			TakeLandCnt_1Year:       item.TakeLandCnt_1Year,
			SellProjectCnt_1Year:    item.SellProjectCnt_1Year,
			CommencePermitCnt_1Year: item.CommencePermitCnt_1Year,
			PurchaseDemandCnt_1Year: item.PurchaseDemandCnt_1Year,
		}
		contactList := make([]*dto.ContactInfo, 0)
		for _, v := range item.ContactList {
			data := &dto.ContactInfo{
				Name:        v.Name,
				PhoneNumber: utils.GetMobileEncrypt(v.PhoneNumber),
			}
			contactList = append(contactList, data)
		}
		crowdItem.ContactList = contactList

		res.List = append(res.List, crowdItem)
	}
	return res, nil
}

func (s *outboundCrowdService) GetCrowdByRpa(ctx context.Context, request *dto.GetCrowdByRpaRequest) (*dto.GetCrowdByRpaResponse, error) {
	// 获取当前租户 code
	var tenantCode string
	if code, ok := ctx.Value(authorize.TENANT_CODE_KEY).(string); ok {
		tenantCode = code
	}
	requestPb := &pb.GetCrowdByRpaRequest{
		Page:          request.Page,
		PageSize:      request.PageSize,
		ProjectId:     request.ProjectId,
		ShowViewTimes: false,
		TenantCode:    tenantCode,
	}
	resPb, err := s.outboundCrowdRepo.GetCrowdByRpa(ctx, requestPb)

	res := &dto.GetCrowdByRpaResponse{
		List: make([]*dto.GetCrowdByRpaItem, 0),
	}
	if err != nil {
		stark.Logger.Error(ctx, "GetCrowdByRpa，失败:", err)
		return res, err
	}
	res.Total = resPb.Total
	for _, item := range resPb.List {
		crowdItem := &dto.GetCrowdByRpaItem{
			CompanyAddress: item.CompanyAddress,
			CompanyName:    item.CompanyName,
			Id:             item.Id,
			PersonName:     item.PersonName,
			PersonPhone:    utils.GetMobileEncrypt(item.PersonPhone),
			PersonPosition: item.PersonPosition,
			PersonRole:     item.PersonRole,
			PersonSexy:     item.PersonSexy,
			ProjectId:      item.ProjectId,
			RccProjectName: item.RccProjectName,
			SourceType:     item.SourceType,
			SrcId:          item.SrcId,
		}
		res.List = append(res.List, crowdItem)
	}
	return res, nil
}
